package com.example.mybatis.multdb.datasource1;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * Project:spring-boot-mybatis-multdb
 * <p>
 * Title:DatasourceConfig1.java
 * <p>
 * Description:
 * <p>
 * Copyrigth:Jiang Software LTD.co Copyright (c) 2022
 * <p>
 * 
 * @version 1.0
 * @since 1.8
 * @author jiang
 * @history 2022 jiang create
 */

@Configuration
@MapperScan(basePackages = "com.example.mybatis.multdb.mapper1", sqlSessionFactoryRef = "sessionFactory1")
public class DatasourceConfig1 {

	@Bean(name = "datasource1")
	@ConfigurationProperties(prefix = "spring.datasource.test1")
	@Primary
	public DataSource getDatasource() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "sessionFactory1")
	@Primary
	public SqlSessionFactory getSqlSessionFactory(@Qualifier(value = "datasource1") DataSource dataSource) {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSource);
		SqlSessionFactory sqlSessionFactory = null;
		try {
			sqlSessionFactory = sqlSessionFactoryBean.getObject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sqlSessionFactory;
	}

}
